<template>
  <section class="main" v-show="todoList.length" v-cloak>
    <input
      class="toggle-all"
      type="checkbox"
      @change="toggleAllChangeFn($event.target.checked)"
    />
    <ul class="todo-list">
      <li
        v-for="(todoItem, index) in todoList"
        :key="index"
        class="todo"
        :class="{
          completed: todoItem.isCompleted,
          editing: todoItem == editedTodo,
        }"
      >
        <div class="view">
          <input
            class="toggle"
            type="checkbox"
            @click="isCompletedChange(todoItem, index)"
          />
          <label @dblclick="editedTodo = todoItem">{{ todoItem.title }}</label>
          <button class="destroy" @click="delTodoFn(index)"></button>
        </div>
        <input
          class="edit"
          type="text"
          v-model="todoItem.title"
          @keydown.enter="enterUpdateTodo({ todoItem, index })"
        />
      </li>
    </ul>
  </section>
</template>

<script>
import { mapActions, mapState } from "vuex";
export default {
  data() {
    return {
      editedTodo: null,
    };
  },
  methods: {
    ...mapActions("todo", [
      "enterUpdateTodoFn",
      "delTodoFn",
      "toggleAllChangeFn",
    ]),
    async enterUpdateTodo(obj) {
      await this.enterUpdateTodoFn(obj);
      this.editedTodo = null;
    },
    isCompletedChange(todoItem, index) {
      todoItem.isCompleted = !todoItem.isCompleted;
      this.enterUpdateTodoFn({ todoItem, index });
    },
  },
  computed: {
    ...mapState("todo", ["todoList"]),
  },
};
</script>

<style scoped  src="../todo.css">
</style>